<template>
  <view class="container p-4">
    <view class="score-info text-center mb-4">
      <text class="score-title">当前积分</text>
      <text class="score-value">{{ userStore.userInfo.score }}</text>
    </view>

    <!-- 转盘区域 -->
    <view class="wheel-container">
      <!-- 指针 -->
      <view class="wheel-arrow"></view>
      
      <canvas 
        canvas-id="luckeyWheel"
        id="luckeyWheel"
        class="wheel-canvas"
        @touchstart="handleTouchStart"
      ></canvas>
      <view class="wheel-pointer" @tap="startRotate">
        <text>开始\n抽奖</text>
      </view>
    </view>

    <!-- 抽奖规则说明 -->
    <view class="rules-container mt-4">
      <view class="rules-title">
        <text class="bi bi-info-circle"></text>
        抽奖规则
      </view>
      <view class="rules-content">
        <text>1. 每次抽奖消耗20积分</text>
        <text>2. 答题获得积分可用于抽奖</text>
        <text>3. 每日登录可获得5积分</text>
        <text>4. 中奖后可在个人中心查看</text>
      </view>
    </view>

    <!-- 中奖记录 -->
    <view class="prize-history mt-4">
      <view class="history-title">
        <text class="bi bi-clock-history"></text>
        中奖记录
      </view>
      <view class="history-list">
        <view v-if="store.prizeHistory.length === 0" class="empty-history">
          暂无中奖记录
        </view>
        <view 
          v-else 
          v-for="(item, index) in store.prizeHistory" 
          :key="index"
          class="history-item"
        >
          <view class="prize-info">
            <text class="user-name">{{ item.userName }}</text>
            <text class="prize-name">{{ item.name }}</text>
          </view>
          <text class="prize-time">{{ item.time }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useCounterStore } from '@/stores/counter';
import { useUserStore } from '@/stores/userStore';

const store = useCounterStore();
const userStore = useUserStore();
let isRotating = false;
let ctx;
let canvasWidth;
let canvasHeight;
let centerX;
let centerY;

// 奖品配置
const prizes = [
  { name: '墨枢笔记本', color: '#ff4444' },
  { name: '墨枢项链系列', color: '#ff8800' },
  { name: '墨枢纪念币', color: '#ffcc00' },
  { name: '墨枢T恤', color: '#44bb00' },
  { name: '谢谢参与', color: '#ff0088' },
  { name: '墨枢徽章', color: '#00ccff' },
  { name: '墨枢陶瓷马克杯', color: '#8800ff' },
  { name: '墨枢鼠标垫', color: '#ff4488' }
];

// 修改初始化转盘函数
const initWheel = () => {
  // 修改创建查询对象的方式
  const query = uni.createSelectorQuery();
  query.select('#luckeyWheel')
    .fields({ node: true, size: true })
    .exec((res) => {
      if (!res[0]) return;
      
      // #ifdef MP-WEIXIN
      const canvas = res[0].node;
      ctx = canvas.getContext('2d');
      const dpr = uni.getSystemInfoSync().pixelRatio;
      canvas.width = res[0].width * dpr;
      canvas.height = res[0].height * dpr;
      ctx.scale(dpr, dpr);
      // #endif
      
      // #ifndef MP-WEIXIN
      ctx = uni.createCanvasContext('luckeyWheel');
      // #endif
      
      canvasWidth = res[0].width;
      canvasHeight = res[0].height;
      centerX = canvasWidth / 2;
      centerY = canvasHeight / 2;
      drawWheel();
    });
};

// 修改绘制转盘函数
const drawWheel = () => {
  const anglePerPrize = (Math.PI * 2) / prizes.length;
  
  // #ifdef MP-WEIXIN
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  // #endif
  
  prizes.forEach((prize, index) => {
    // #ifdef MP-WEIXIN
    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.arc(
      centerX,
      centerY,
      Math.min(centerX, centerY) - 10,
      index * anglePerPrize,
      (index + 1) * anglePerPrize
    );
    ctx.closePath();
    ctx.fillStyle = prize.color;
    ctx.fill();
    
    // 绘制文字
    ctx.save();
    ctx.translate(centerX, centerY);
    ctx.rotate(index * anglePerPrize + anglePerPrize / 2);
    ctx.textAlign = 'right';
    ctx.fillStyle = '#fff';
    ctx.font = '12px Arial';
    ctx.fillText(prize.name, Math.min(centerX, centerY) - 30, 0);
    ctx.restore();
    // #endif
    
    // #ifndef MP-WEIXIN
    ctx.beginPath();
    ctx.moveTo(centerX, centerY);
    ctx.arc(
      centerX,
      centerY,
      Math.min(centerX, centerY) - 10,
      index * anglePerPrize,
      (index + 1) * anglePerPrize
    );
    ctx.setFillStyle(prize.color);
    ctx.fill();
    
    // 绘制文字
    ctx.save();
    ctx.translate(centerX, centerY);
    ctx.rotate(index * anglePerPrize + anglePerPrize / 2);
    ctx.setTextAlign('right');
    ctx.setFillStyle('#fff');
    ctx.setFontSize(12);
    ctx.fillText(prize.name, Math.min(centerX, centerY) - 30, 0);
    ctx.restore();
    // #endif
  });
  
  // #ifndef MP-WEIXIN
  ctx.draw();
  // #endif
};

// 修改开始抽奖函数，使用 userStore.updateUserScore
const startRotate = () => {
  if (isRotating) return;
  
  // 检查userStore中的积分是否足够
  if (!userStore.userInfo || userStore.userInfo.score < 20) {
    uni.showToast({
      title: '积分不足',
      icon: 'none'
    });
    return;
  }
  
  // 使用专门的积分操作方法扣除积分
  userStore.updateUserScore(-20);
  
  isRotating = true;
  
  const index = Math.floor(Math.random() * prizes.length);
  const prize = prizes[index];
  
  // 计算旋转角度
  const targetAngle = 360 * 5 + (360 / prizes.length) * index;
  let currentAngle = 0;
  let lastTime = Date.now();
  
  const animate = () => {
    const now = Date.now();
    const deltaTime = now - lastTime;
    lastTime = now;
    
    if (currentAngle >= targetAngle) {
      isRotating = false;
      handlePrize(prize);
      return;
    }
    
    currentAngle += (deltaTime / 16) * 10; // 使动画更平滑
    
    // #ifdef MP-WEIXIN
    ctx.save();
    ctx.translate(centerX, centerY);
    ctx.rotate(Math.PI / 180 * currentAngle);
    ctx.translate(-centerX, -centerY);
    drawWheel();
    ctx.restore();
    // #endif
    
    // #ifndef MP-WEIXIN
    ctx.translate(centerX, centerY);
    ctx.rotate(Math.PI / 180 * currentAngle);
    ctx.translate(-centerX, -centerY);
    drawWheel();
    // #endif
    
    requestAnimationFrame(animate);
  };
  
  animate();
};

// 处理中奖
const handlePrize = (prize) => {
  if (prize.name !== '谢谢参与') {
    store.addPrizeHistory({
      name: prize.name,
      userName: userStore.userInfo?.user_name || '小傩',
      time: new Date().toLocaleString()
    });
    
    uni.showToast({
      title: `恭喜获得${prize.name}`,
      icon: 'success'
    });
  } else {
    uni.showToast({
      title: '谢谢参与，下次一定',
      icon: 'none'
    });
  }
};

// 备用抽奖函数（总是谢谢参与）
const backupStartRotate = () => {
  if (isRotating) return;
  
  if (!userStore.userInfo || userStore.userInfo.score < 20) {
    uni.showToast({
      title: '积分不足',
      icon: 'none'
    });
    return;
  }
  
  // 使用专门的积分操作方法扣除积分
  userStore.updateUserScore(-20);
  
  isRotating = true;
  
  // 找到"谢谢参与"的索引
  const thanksIndex = prizes.findIndex(p => p.name === '谢谢参与');
  
  // 计算旋转角度
  const targetAngle = 360 * 5 + (360 / prizes.length) * thanksIndex;
  
  // 执行旋转动画
  let currentAngle = 0;
  const animate = () => {
    if (currentAngle >= targetAngle) {
      isRotating = false;
      handlePrize(prizes[thanksIndex]);
      return;
    }
    
    currentAngle += 10;
    ctx.translate(centerX, centerY);
    ctx.rotate(Math.PI / 180 * 10);
    ctx.translate(-centerX, -centerY);
    drawWheel();
    requestAnimationFrame(animate);
  };
  
  animate();
};

onMounted(() => {
  // 延迟初始化以确保 canvas 已经渲染
  setTimeout(() => {
    initWheel();
  }, 100);
  
  // 确保用户已登录并初始化用户信息
  if (!userStore.isLoggedIn) {
    uni.showToast({
      title: '请先登录后再抽奖',
      icon: 'none',
      duration: 2000
    });
    
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/other/login'
      });
    }, 2000);
    return;
  }
  
  // 确保用户信息中有积分字段
  if (userStore.userInfo && !userStore.userInfo.score) {
    // 如果用户信息存在但积分字段不存在，初始化为0
    userStore.updateUserInfoLocal({
      score: 0
    });
  }
  
  // 初始化历史记录
  if (store.prizeHistory.length === 0) {
    store.addPrizeHistory({
      name: '傩韵手机壳',
      userName: userStore.userInfo?.user_name || '小傩',
      time: '2024-03-20 10:30:00'
    });
    store.addPrizeHistory({
      name: '赣傩文化帆布包',
      userName: '小赣',
      time: '2024-03-19 15:45:00'
    });
  }
});
</script>

<style lang="scss" scoped>
.score-info {
  background: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  
  .score-title {
    font-size: 28rpx;
    color: #666;
    margin-right: 20rpx;
  }
  
  .score-value {
    font-size: 40rpx;
    color: var(--td-brand-color);
    font-weight: bold;
  }
}

.wheel-container {
  position: relative;
  width: 600rpx;
  height: 600rpx;
  margin: 40rpx auto;
  border-radius: 50%;
  box-shadow: 0 0 20rpx rgba(0,0,0,0.1);
  
  &::before {
    content: '';
    position: absolute;
    top: -10rpx;
    left: -10rpx;
    right: -10rpx;
    bottom: -10rpx;
    border: 10rpx solid var(--td-brand-color);
    border-radius: 50%;
    z-index: 0;
  }
}

.wheel-arrow {
  position: absolute;
  top: -20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 20rpx solid transparent;
  border-right: 20rpx solid transparent;
  border-bottom: 40rpx solid var(--td-brand-color);
  z-index: 2;
}

.wheel-canvas {
  width: 100%;
  height: 100%;
}

.wheel-pointer {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100rpx;
  height: 100rpx;
  background: var(--td-brand-color);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 24rpx;
  text-align: center;
  z-index: 1;
  
  &:active {
    transform: translate(-50%, -50%) scale(0.95);
  }
}

.rules-container, .prize-history {
  background: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  
  .rules-title, .history-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    gap: 10rpx;
    
    .bi {
      color: var(--td-brand-color);
    }
  }
}

.rules-content {
  text {
    display: block;
    font-size: 26rpx;
    color: #666;
    line-height: 1.8;
  }
}

.history-list {
  .empty-history {
    text-align: center;
    color: #999;
    font-size: 26rpx;
    padding: 40rpx 0;
  }
  
  .history-item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    border-bottom: 2rpx solid #f5f5f5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .prize-info {
      display: flex;
      gap: 20rpx;
      align-items: center;
      
      .user-name {
        color: var(--td-brand-color);
        font-size: 28rpx;
        font-weight: bold;
      }
      
      .prize-name {
        color: #333;
        font-size: 28rpx;
      }
    }
    
    .prize-time {
      color: #999;
      font-size: 24rpx;
    }
  }
}
</style>

